package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.annotation.SessionScope;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

@Controller
@SessionScope
@RequestMapping("/cart")
@SessionAttributes("cart")
public class CartController {
    @Autowired
    private CatalogService catalogService;
    @Autowired
    private Cart cart;

    @GetMapping("/viewCart")
    public String viewCart(Model model){
        model.addAttribute("cart",cart);
        return "cart/cart";
    }

    @GetMapping("/addItemToCart")
    public String addItemToCart (String workingItemId, Model model){
        Item item1 = catalogService.getItem(workingItemId);

            if (item1.getQuantity() == 0){
                String msg = "库存不足，请您浏览其他商品";
                model.addAttribute("msg",msg);
                return "catalog/main";
            }
        if (cart.containsItemId(workingItemId)){
            cart.incrementQuantityByItemId(workingItemId);
        }else {
            boolean isInstock = catalogService.isItemInStock((workingItemId));
            Item item = catalogService.getItem(workingItemId);
            cart.addItem(item,isInstock);
        }
        model.addAttribute("cart",cart);
        return "cart/cart";
    }

    @GetMapping("removeItemFromCart")
    public String removeItemFromCart (String workingItemId, Model model){
        Item item = cart.removeItemById(workingItemId);
        model.addAttribute("cart",cart);
        if (item == null){
            model.addAttribute("msg","Attempted to remove null CartItem from Cart");
            return "common/error";
        }else{
            return "cart/cart";
        }
    }

    @PostMapping("updateCartQuantities")
    public String updateCartQuantities(HttpServletRequest request, Model model){
        Iterator<CartItem> cartItems = cart.getAllCartItems();
        while (cartItems.hasNext()){
            CartItem cartItem = cartItems.next();
            String itemId = cartItem.getItem().getItemId();
            try{
                int quantity = Integer.parseInt(request.getParameter(itemId));
                cart.setQuantityByItemId(itemId,quantity);
                if (quantity < 1){
                    cartItems.remove();
                }
            }catch (Exception e){
                System.out.println("error");
            }
        }
        model.addAttribute("cart",cart);
        return"cart/cart";
    }

@GetMapping("updateCart")
@ResponseBody
    public void updateCart (HttpServletRequest request, HttpServletResponse response) throws IOException {
    Cart cart;

        //从对话中，获取购物车
        //System.out.print(" 2112121");
        HttpSession session = request.getSession();
        cart = (Cart)session.getAttribute("cart");
        Iterator<CartItem> cartItemIterator = cart.getAllCartItems();

        while (cartItemIterator.hasNext()) {
            //产品数量增加
            CartItem cartItem = (CartItem) cartItemIterator.next();
            String itemId = cartItem.getItem().getItemId();

            try {
                int quantity = Integer.parseInt((String) request.getParameter("quantity"));
                System.out.println(quantity);
                cart.setQuantityByItemId(itemId, quantity);
                if (quantity < 1) {
                    cartItemIterator.remove();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        ((HttpSession) session).setAttribute("cart", cart);


        Cart cart2 = (Cart)session.getAttribute("cart");
        Iterator<CartItem> cartItemIterator2 = cart2.getAllCartItems();
        String quantityAll = "";
        while (cartItemIterator2.hasNext()) {
            //产品数量增加
            CartItem cartItem2 = cartItemIterator2.next();
            int quantity2 = cartItem2.getQuantity();
            quantityAll += quantity2 + "," + cartItem2.getTotal() + "," + cart2.getSubTotal();

        }

        PrintWriter out = response.getWriter();
        out.write(quantityAll);

    }





}

